<template>
  <view class="edit-profile-page">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="nav-back" @tap="goBack">
        <text class="iconfont back-icon">&#xe697;</text>
      </view>
      <text class="page-title">编辑资料</text>
    </view>
    
    <view class="edit-container">
      <!-- 头像修改区域 -->
      <view class="avatar-section">
        <view class="avatar-wrapper" @tap="chooseAvatar">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
          <view class="avatar-overlay">
            <text class="overlay-text">更换头像</text>
          </view>
        </view>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 昵称区域 -->
        <view class="form-group">
          
          <view class="form-item">
            <view class="item-label">
              <text class="label-text">昵称</text>
            </view>
            <view class="item-content">
              <input 
                class="input-field" 
                type="text" 
                v-model="userInfo.nickname" 
                placeholder="请输入昵称" 
                maxlength="20"
              />
            </view>
          </view>
        </view>
        
        <!-- 手机号区域 -->
        <view class="form-group">
          
          <!-- 当前手机号 -->
          <view class="form-item info-item">
            <view class="item-label">
              <text class="label-text">手机号</text>
            </view>
            <view class="item-content">
              <text class="info-text">{{formatPhone(userInfo.phone)}}</text>
            </view>
          </view>
          
          <!-- 新手机号 -->
          <view class="form-item" v-if="showPhoneChange">
            <view class="item-label">
              <text class="label-text">新手机号</text>
            </view>
            <view class="item-content">
              <input 
                class="input-field" 
                type="number" 
                v-model="newPhone" 
                placeholder="请输入新手机号" 
                maxlength="11"
              />
            </view>
          </view>
          
          <!-- 手机验证码 -->
          <view class="form-item" v-if="showPhoneChange">
            <view class="item-label">
              <text class="label-text">验证码</text>
            </view>
            <view class="item-content code-content">
              <input 
                class="input-field" 
                type="number" 
                v-model="phoneVerifyCode" 
                placeholder="请输入验证码" 
                maxlength="6"
              />
              <view 
                class="verify-btn" 
                :class="{ 'disabled': cooldown > 0 }" 
                @tap="sendVerifyCode"
              >
                <text>{{cooldown > 0 ? `${cooldown}秒后重发` : '获取验证码'}}</text>
              </view>
            </view>
          </view>
          
          <!-- 手机号修改按钮 -->
          <view class="action-btn-wrapper">
            <button 
              class="action-btn" 
              v-if="!showPhoneChange" 
              @tap="togglePhoneChange"
            >
              修改手机号
            </button>
            <button 
              class="action-btn submit-btn" 
              v-else 
              @tap="updatePhone" 
              :disabled="!isPhoneFormValid"
            >
              确认修改
            </button>
            <button 
              class="action-btn cancel-btn" 
              v-if="showPhoneChange" 
              @tap="togglePhoneChange"
            >
              取消
            </button>
          </view>
        </view>
        
        <!-- 密码修改区域 -->
        <view class="form-group">
          <view class="group-title">
            <text class="title-text">密码</text>
          </view>
          
          <!-- 当前密码 -->
          <view class="form-item" v-if="showPasswordChange">
            <view class="item-label">
              <text class="label-text">当前密码</text>
            </view>
            <view class="item-content">
              <input 
                class="input-field" 
                type="password" 
                v-model="currentPassword" 
                placeholder="请输入当前密码" 
                password
              />
            </view>
          </view>
          
          <!-- 新密码 -->
          <view class="form-item" v-if="showPasswordChange">
            <view class="item-label">
              <text class="label-text">新密码</text>
            </view>
            <view class="item-content">
              <input 
                class="input-field" 
                type="password" 
                v-model="newPassword" 
                placeholder="请输入新密码" 
                password
              />
            </view>
          </view>
          
          <!-- 确认新密码 -->
          <view class="form-item" v-if="showPasswordChange">
            <view class="item-label">
              <text class="label-text">确认密码</text>
            </view>
            <view class="item-content">
              <input 
                class="input-field" 
                type="password" 
                v-model="confirmPassword" 
                placeholder="请再次输入新密码" 
                password
              />
            </view>
          </view>
          
          <!-- 密码修改操作按钮 -->
          <view class="action-btn-wrapper">
            <button 
              class="action-btn" 
              v-if="!showPasswordChange" 
              @tap="togglePasswordChange"
            >
              修改密码
            </button>
            <button 
              class="action-btn submit-btn" 
              v-else 
              @tap="updatePassword" 
              :disabled="!isPasswordFormValid"
            >
              确认修改
            </button>
            <button 
              class="action-btn cancel-btn" 
              v-if="showPasswordChange" 
              @tap="togglePasswordChange"
            >
              取消
            </button>
          </view>
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <view class="save-btn-wrapper">
        <button class="save-btn" @tap="saveProfile">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';

// 用户信息
const userInfo = reactive({
  avatar: '../../image/R.jpg',
  nickname: '',
  phone: '',
});

// 表单显示状态
const showPhoneChange = ref(false);
const showPasswordChange = ref(false);

// 手机修改相关
const newPhone = ref('');
const phoneVerifyCode = ref('');
const cooldown = ref(0);

// 密码修改相关
const currentPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');

// 页面加载时获取当前用户信息
onMounted(() => {
  loadUserInfo();
});

// 加载用户信息
const loadUserInfo = () => {
  const userInfoStr = uni.getStorageSync('userInfo');
  if (userInfoStr) {
    try {
      const info = JSON.parse(userInfoStr);
      userInfo.nickname = info.name || '';
      userInfo.phone = info.phone || '';
      userInfo.avatar = info.avatar || '../../image/R.jpg';
    } catch (error) {
      console.error('解析用户信息失败:', error);
    }
  }
};

// 格式化手机号
const formatPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone;
  return phone.slice(0, 3) + '****' + phone.slice(7);
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      // 预览裁剪
      uni.navigateTo({
        url: `/pages/profile/crop-avatar?avatar=${encodeURIComponent(tempFilePath)}`
      });
      
      // 这里简单处理，直接使用选择的图片
      userInfo.avatar = tempFilePath;
    }
  });
};

// 切换手机号修改显示
const togglePhoneChange = () => {
  showPhoneChange.value = !showPhoneChange.value;
  if (!showPhoneChange.value) {
    // 重置相关字段
    newPhone.value = '';
    phoneVerifyCode.value = '';
    cooldown.value = 0;
  }
};

// 切换密码修改显示
const togglePasswordChange = () => {
  showPasswordChange.value = !showPasswordChange.value;
  if (!showPasswordChange.value) {
    // 重置相关字段
    currentPassword.value = '';
    newPassword.value = '';
    confirmPassword.value = '';
  }
};

// 发送验证码
const sendVerifyCode = () => {
  if (cooldown.value > 0) return;
  
  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(newPhone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  // 模拟发送验证码
  uni.showLoading({ title: '发送中...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    // 开始倒计时
    cooldown.value = 60;
    const timer = setInterval(() => {
      cooldown.value--;
      if (cooldown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
    
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
  }, 1500);
};

// 手机表单验证
const isPhoneFormValid = computed(() => {
  return (
    newPhone.value && 
    newPhone.value.length === 11 && 
    phoneVerifyCode.value && 
    phoneVerifyCode.value.length === 6
  );
});

// 密码表单验证
const isPasswordFormValid = computed(() => {
  return (
    currentPassword.value && 
    newPassword.value && 
    confirmPassword.value && 
    newPassword.value === confirmPassword.value &&
    newPassword.value.length >= 6
  );
});

// 更新手机号
const updatePhone = () => {
  if (!isPhoneFormValid.value) return;
  
  // 模拟验证验证码
  uni.showLoading({ title: '验证中...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    // 假设验证成功
    userInfo.phone = newPhone.value;
    
    // 重置表单
    togglePhoneChange();
    
    uni.showToast({
      title: '手机号修改成功',
      icon: 'success'
    });
  }, 1500);
};

// 更新密码
const updatePassword = () => {
  if (!isPasswordFormValid.value) return;
  
  // 验证当前密码是否正确
  uni.showLoading({ title: '验证中...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    // 假设验证成功
    // 重置表单
    togglePasswordChange();
    
    uni.showToast({
      title: '密码修改成功',
      icon: 'success'
    });
  }, 1500);
};

// 保存资料
const saveProfile = () => {
  uni.showLoading({ title: '保存中...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    // 更新存储的用户信息
    const userInfoData = {
      name: userInfo.nickname,
      phone: userInfo.phone,
      avatar: userInfo.avatar
    };
    
    uni.setStorageSync('userInfo', JSON.stringify(userInfoData));
    
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      success: () => {
        // 延迟返回
        setTimeout(() => {
          // 返回个人中心页面
          uni.switchTab({
            url: '/pages/profile/index'
          });
        }, 1500);
      }
    });
  }, 1500);
};

// 返回上一页
const goBack = () => {
  // 返回个人中心页面
  uni.switchTab({
    url: '/pages/profile/index'
  });
};
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
  min-height: 100%;
}

.edit-profile-page {
  padding-bottom: 30px;
  
  .header {
    position: relative;
    display: flex;
    align-items: center;
    height: 44px;
    background-color: #fff;
    border-bottom: 1px solid rgba(195, 227, 227, 0.2);
    
    .nav-back {
      position: absolute;
      left: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .back-icon {
        font-size: 20px;
        color: #5d4037;
      }
    }
    
    .page-title {
      flex: 1;
      text-align: center;
      font-size: 18px;
      font-weight: 500;
      color: #5d4037;
    }
  }
  
  .edit-container {
    padding: 20px 15px;
    
    .avatar-section {
      display: flex;
      justify-content: center;
      margin-bottom: 30px;
      
      .avatar-wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        
        .avatar {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .avatar-overlay {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 30px;
          background-color: rgba(44, 120, 115, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          
          .overlay-text {
            color: #fff;
            font-size: 12px;
          }
        }
      }
    }
    
    .form-section {
      .form-group {
        background-color: #fff;
        border-radius: 12px;
        margin-bottom: 15px;
        overflow: hidden;
        
        .group-title {
          padding: 12px 15px;
          border-bottom: 1px solid rgba(195, 227, 227, 0.2);
          
          .title-text {
            font-size: 16px;
            font-weight: 500;
            color: #5d4037;
          }
        }
      }
      
      .form-item {
        display: flex;
        align-items: center;
        background-color: #fff;
        padding: 12px 15px;
        border-bottom: 1px solid rgba(195, 227, 227, 0.2);
        
        &:last-child {
          border-bottom: none;
        }
        
        &.info-item {
          background-color: rgba(195, 227, 227, 0.05);
        }
        
        .item-label {
          width: 100px;
          
          .label-text {
            font-size: 15px;
            color: #5d4037;
          }
        }
        
        .item-content {
          flex: 1;
          
          .input-field {
            width: 100%;
            height: 30px;
            font-size: 15px;
            color: #5d4037;
          }
          
          .info-text {
            font-size: 15px;
            color: #8d6e63;
          }
          
          &.code-content {
            display: flex;
            align-items: center;
            
            .input-field {
              flex: 1;
            }
            
            .verify-btn {
              padding: 6px 12px;
              background-color: #6FB3B8;
              border-radius: 4px;
              margin-left: 10px;
              
              text {
                font-size: 14px;
                color: #fff;
              }
              
              &.disabled {
                background-color: #ccc;
              }
            }
          }
        }
      }
      
      .action-btn-wrapper {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        
        .action-btn {
          flex: 1;
          height: 40px;
          line-height: 40px;
          text-align: center;
          font-size: 15px;
          border-radius: 20px;
          background-color: #fff;
          color: #6FB3B8;
          border: 1px solid #6FB3B8;
          margin: 0 5px;
          
          &.submit-btn {
            background-color: #6FB3B8;
            color: #fff;
            border: none;
            
            &[disabled] {
              background-color: #ccc;
              color: #fff;
            }
          }
          
          &.cancel-btn {
            color: #999;
            border: 1px solid #ddd;
          }
        }
      }
    }
    
    .save-btn-wrapper {
      margin-top: 30px;
      padding: 0 15px;
      
      .save-btn {
        width: 100%;
        height: 45px;
        line-height: 45px;
        text-align: center;
        font-size: 16px;
        color: #fff;
        background-color: #2c7873;
        border-radius: 22.5px;
        box-shadow: 0 4px 12px rgba(44, 120, 115, 0.2);
      }
    }
  }
}
</style> 